<!DOCTYPE html>
<html>
<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  <div id="status">Loading 0%</div>

  <script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const statusDiv = document.getElementById('status');

    // 初始化灰色背景
    ctx.fillStyle = '#eee';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 接收分块数据
    let receivedBytes = 0;
    let totalBytes = 0;

    fetch('http://localhost:4000/chunked-image')
      .then(response => {
        const reader = response.body.getReader();
        const chunks = [];

        // 逐块处理
        function processChunk({ done, value }) {
          if (done) {
            // 合并所有块并渲染最终图片
            const blob = new Blob(chunks, { type: 'image/jpeg' });
            const url = URL.createObjectURL(blob);
            const img = new Image();
            img.onload = () => {
              ctx.drawImage(img, 0, 0);
              URL.revokeObjectURL(url);
            };
            img.src = url;
            return;
          }

          // 记录总字节数（如果后端提供）
          if (totalBytes === 0 && response.headers.get('Content-Length')) {
            totalBytes = parseInt(response.headers.get('Content-Length'));
          }

          // 更新接收数据
          receivedBytes += value.length;
          chunks.push(value);
          updateProgress();

          // 实时渲染到Canvas
          const currentBlob = new Blob(chunks, { type: 'image/jpeg' });
          const img = new Image();
          img.onload = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0);
          };
          img.src = URL.createObjectURL(currentBlob);

          // 继续读取下一块
          return reader.read().then(processChunk);
        }

        return reader.read().then(processChunk);
      });

    // 更新加载进度
    function updateProgress() {
      const percent = totalBytes > 0 
        ? Math.round((receivedBytes / totalBytes) * 100)
        : '--';
      statusDiv.textContent = `Loading ${percent}%`;
    }
  </script>
</body>
</html>